//
//  HHPHttpChainRequest.m
//  HHPHTTPRequest
//
//  Created by 韩红坡 on 2017/1/16.
//  Copyright © 2017年 韩红坡. All rights reserved.
//

#import "HHPHTTPChainRequest.h"
#import "HHPHTTPRequest.h"

@interface HHPHTTPChainRequest ()

@property (nonatomic, strong) NSMutableArray *requestBlocks;
@property (nonatomic, strong) NSMutableArray *mutableRequests;
@property (nonatomic, assign) NSUInteger currentRequestIndex;
@property (nonatomic, strong) void (^successBlock)(HHPHTTPChainRequest *);
@property (nonatomic, strong) void (^errorBlock)(HHPHTTPChainRequest *);

@end

@implementation HHPHTTPChainRequest

- (instancetype)init
{
    self = [super init];
    if (self) {
        _requestBlocks = [NSMutableArray array];
        _mutableRequests = [NSMutableArray array];
        _currentRequestIndex = 0;
    }
    
    return self;
}

- (void)addRequestBlock:(HHPHTTPRequest *(^)(HHPHTTPRequest *))requestBlock
{
    [self.requestBlocks addObject:[requestBlock copy]];
}

- (void)startWithSuccess:(void (^)(HHPHTTPChainRequest *))successBlock error:(void (^)(HHPHTTPChainRequest *))errorBlock
{
    if (self.mutableRequests.count <= 0 && self.requestBlocks.count > 0) {
        self.successBlock = successBlock;
        self.errorBlock = errorBlock;
        [self nextRequest:nil];
    }
}

- (void)nextRequest:(HHPHTTPRequest *)previousRequest
{
    if (self.currentRequestIndex + 1 > self.requestBlocks.count) {
        if (self.successBlock) {
            self.successBlock(self);
        }
    } else {
        HHPHTTPRequest *(^requestBlock)(HHPHTTPRequest *previousRequest) = self.requestBlocks[self.currentRequestIndex];
        HHPHTTPRequest *newRequest = requestBlock(previousRequest);
        [self.mutableRequests addObject:newRequest];
        self.currentRequestIndex += 1;
        
        // 此处不会发生循环引用
        // 在请求完成后，HHPHTTPRequest会主动释放回调block
        [newRequest startWithSuccess:^(HHPHTTPRequest *request) {
            [self nextRequest:request];
        } error:^(HHPHTTPRequest *request) {
            if (self.errorBlock) {
                self.errorBlock(self);
            }
        }];
    }
}

- (void)cancel
{
    [self.mutableRequests.lastObject cancel];
}

- (NSArray<HHPHTTPRequest *> *)requests
{
    return [self.mutableRequests copy];
}

@end
